package com.sdkj.dspservice.modules.report.utils.hive;

import com.alibaba.druid.pool.DruidDataSource;
import com.sdkj.dspservice.common.enums.DataTypeEnum;
import com.sdkj.dspservice.modules.report.entity.Source;
import com.sdkj.dspservice.modules.report.entity.tem.QueryColumn;
import lombok.Data;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * hive工具类
 *
 * @author tm
 * @version 2020/12/15 17:24
 */
@Data
public class HiveUtils {

    private static final String TABLE = "TABLE";
    private static final String VIEW = "VIEW";
    private static final String[] TABLE_TYPES = new String[]{TABLE, VIEW};
    private static final String TABLE_NAME = "TABLE_NAME";
    private static final String TABLE_TYPE = "TABLE_TYPE";

    private Connection connection;
    private Statement statement;
    private ResultSet resultSet;
    private DruidDataSource datasource;

//    private HiveConf hiveConf;
//    private HiveMetaStoreClient client;
    /**
     * 数据源类型
     */
    private DataTypeEnum dataTypeEnum;

    public HiveUtils(String url, String username, String password) {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(url);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName("org.apache.hive.jdbc.HiveDriver");

        // pool configuration
        datasource.setInitialSize(1);
        datasource.setMinIdle(3);
        datasource.setMaxActive(20);
        datasource.setMaxWait(60000);
        datasource.setTimeBetweenEvictionRunsMillis(60000);
        datasource.setMinEvictableIdleTimeMillis(30000);
        datasource.setValidationQuery("select 1");
        datasource.setTestWhileIdle(true);
        datasource.setTestOnBorrow(false);
        datasource.setTestOnReturn(false);
        datasource.setPoolPreparedStatements(true);
        datasource.setMaxPoolPreparedStatementPerConnectionSize(20);
        // 解决连接失败时，不停打印日志的情况
        datasource.setBreakAfterAcquireFailure(true);
        try {
            this.datasource = datasource;
            connection = datasource.getConnection();
            statement = connection.createStatement();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public HiveUtils(Source source) {
        this(source.getDatabaseUrl(), source.getDatabaseUsername(), source.getDatabasePassword());
    }

    public void destruction() throws SQLException {
        if (resultSet != null) {
            resultSet.close();
        }
        if (statement != null) {
            statement.close();
        }
        if (connection != null) {
            connection.close();
        }
    }

    /**
     * 运行SQL
     *
     * @param sql
     * @return
     */
    public ResultSet runSql(String sql) {
        try {
            System.out.println("********************************************************");
            System.out.println(sql);
            System.out.println("********************************************************");
            resultSet = statement.executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;
    }

    public List<QueryColumn> getTableColumnList(String tableName){
        List<QueryColumn> columnList = null;
        ResultSet tables = null;
        try {
            tables = statement.executeQuery("desc " + tableName);
            columnList = new ArrayList<>();
            while (tables.next()) {
                // 当字段名出现#时，说明开始遍历hive的说明字段了，说明字段后面为分区字段，都不记录
                if(tables.getString("col_name").indexOf("#") != -1){
                    break;
                }
                columnList.add(new QueryColumn(tables.getString("col_name"), tables.getString("data_type"), tables.getString("comment")));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                destruction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return columnList;
    }

    public List<String> getTableNameList(){
        List<String> tableList = null;
        ResultSet tables = null;
        try {
            tables = statement.executeQuery("show tables");
            tableList = new ArrayList<>();
            while (tables.next()) {
                String name = tables.getString("tableName");
                if (!com.alibaba.druid.util.StringUtils.isEmpty(name)) {
                    tableList.add(name);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                destruction();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return tableList;
    }

}
